package com.example.videoweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.videoweb.domain.Collections;
import com.example.videoweb.domain.Consumer;
import com.example.videoweb.domain.History;
import com.example.videoweb.domain.Praise;
import com.example.videoweb.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private CollectionService collectionService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private PraiseService praiseService;
    @Autowired
    private StatisticalService statisticalService;

    //添加用户
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object addConsumer(@RequestParam("file") MultipartFile file,
                              @RequestParam("username") String username,
                              @RequestParam("password") String password,
                              @RequestParam("sex") String sex,
                              @RequestParam("email") String email,
                              @RequestParam("birth") String birth,
                              @RequestParam("introduction") String introduction){
        JSONObject jsonObject = new JSONObject();

        if(username == null||username.equals("")){
            jsonObject.put("code",0);
            jsonObject.put("msg","用户名不能为空");
            return jsonObject;
        }
        Consumer consumer1 = consumerService.getByUsername(username);
        if(consumer1 != null){
            jsonObject.put("code",0);
            jsonObject.put("msg","用户名已存在");
            return jsonObject;
        }
        if(password == null||password.equals("")){
            jsonObject.put("code",0);
            jsonObject.put("msg","密码不能为空");
            return jsonObject;
        }

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDate = new Date();
        try {
            birthDate = dateFormat.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Consumer consumer = new Consumer();
        consumer.setUsername(username);
        consumer.setPassword(password);
        consumer.setSex(new Byte(sex));
        consumer.setEmail(email);
        consumer.setBirth(birthDate);
        consumer.setIntroduction(introduction);

        String storeAvatarImagesPath;

        if (!file.isEmpty()){
            //文件名=当前时间的毫秒+原来的文件名
            String fileName = System.currentTimeMillis()+file.getOriginalFilename();  //头像
            //文件路径
            String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"avatarImages";
            //如果文件路径不存在，新增该路径
            File file1 = new File(filePath);
            if(!file1.exists()){
                file1.mkdir();
            }
            //实际的文件地址
            File dest = new File(filePath+System.getProperty("file.separator")+fileName);
            //存储到数据库里的相对文件地址
            storeAvatarImagesPath = "/avatarImages/"+fileName;
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            storeAvatarImagesPath = "/avatarImages/user.jpg";
        }

        consumer.setAvatar(storeAvatarImagesPath);
        boolean flag = consumerService.insert(consumer);


        if (flag) {
            if (Integer.parseInt(sex) == 1){
                statisticalService.numUp("boy");
            }else{
                statisticalService.numUp("girl");
            }
            jsonObject.put("code",1);
            jsonObject.put("msg","添加成功");
            return jsonObject;
        }
        jsonObject.put("code",0);
        jsonObject.put("msg","添加失败");
        return jsonObject;
    }
    //修改用户信息
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object updateConsumer(@RequestParam("file") MultipartFile file,
                                 @RequestParam("id") String id,
                                 @RequestParam("username") String username,
                                 @RequestParam("password") String password,
                                 @RequestParam("sex") String sex,
                                 @RequestParam("email") String email,
                                 @RequestParam("birth") String birth,
                                 @RequestParam("introduction") String introduction) {
        JSONObject jsonObject = new JSONObject();

        if(username == null||username.equals("")){
            jsonObject.put("code",0);
            jsonObject.put("msg","用户名不能为空");
            return jsonObject;
        }
        Consumer consumer1 = consumerService.getByUsername(username);
        if(consumer1 != null&& consumer1.getId() != Integer.parseInt(id)){
            jsonObject.put("code",0);
            jsonObject.put("msg","用户名已存在");
            return jsonObject;
        }
        if(password == null||password.equals("")){
            jsonObject.put("code",0);
            jsonObject.put("msg","密码不能为空");
            return jsonObject;
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthDate = new Date();
        try {
            birthDate = dateFormat.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Consumer consumer = new Consumer();
        consumer.setId(Integer.parseInt(id));
        consumer.setUsername(username);
        consumer.setPassword(password);
        consumer.setSex(new Byte(sex));
        consumer.setEmail(email);
        consumer.setBirth(birthDate);
        consumer.setIntroduction(introduction);

        if (!file.isEmpty()){
            //删除原头像
            String url = consumerService.selectByPrimaryKey(Integer.parseInt(id)).getAvatar();
            if(!url.equals("/avatarImages/user.jpg")){
                File file2=new File(System.getProperty("user.dir")+"/"+url);
                if(file2.exists() && file2.isFile()){
                    file2.delete();
                }
            }
            //文件名=当前时间的毫秒+原来的文件名
            String fileName = System.currentTimeMillis()+file.getOriginalFilename();  //头像
            //文件路径
            String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"avatarImages";
            //如果文件路径不存在，新增该路径
            File file1 = new File(filePath);
            if(!file1.exists()){
                file1.mkdir();
            }
            //实际的文件地址
            File dest = new File(filePath+System.getProperty("file.separator")+fileName);
            //存储到数据库里的相对文件地址
            String storeAvatarImagesPath = "/avatarImages/"+fileName;
            consumer.setAvatar(storeAvatarImagesPath);
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        boolean flag = consumerService.update(consumer);
        if (flag) {
            jsonObject.put("code",1);
            jsonObject.put("msg","修改成功");
            return jsonObject;
        }
        jsonObject.put("code",0);
        jsonObject.put("msg","修改失败");
        return jsonObject;
    }
    //删除用户
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    public Object deleteConsumer(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        Consumer consumer = consumerService.selectByPrimaryKey(Integer.parseInt(id));
        //删除头像
        String url = consumer.getAvatar();
        if(!url.equals("/avatarImages/user.jpg")){
            File file2=new File(System.getProperty("user.dir")+"/"+url);
            if(file2.exists() && file2.isFile()){
                file2.delete();
            }
        }
        boolean flag = consumerService.delete(Integer.parseInt(id));
        if (flag){
            Byte sex = consumer.getSex();
            if (sex == 1){
                statisticalService.numDown("boy");
            }else{
                statisticalService.numDown("girl");
            }
        }
        return flag;
    }
    //根据id查询用户
    @RequestMapping(value = "/getById",method = RequestMethod.GET)
    public Object getById(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        return consumerService.selectByPrimaryKey(Integer.parseInt(id));
    }
    //根据id查询用户(带密码
    @RequestMapping(value = "/getById2",method = RequestMethod.GET)
    public Object getById2(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        return consumerService.selectByPrimaryKey2(Integer.parseInt(id));
    }

    //查询所有前端用户
    @RequestMapping(value = "/allConsumer",method = RequestMethod.GET)
    public Object allConsumer(HttpServletRequest request){
        return consumerService.allConsumer();
    }

    //查询所有前端用户(带密码
    @RequestMapping(value = "/allConsumer2",method = RequestMethod.GET)
    public Object allConsumer2(HttpServletRequest request){
        return consumerService.allConsumer2();
    }

    //更新前端用户图片
    @RequestMapping(value = "/updateConsumerPic",method = RequestMethod.POST)
    public Object updateConsumerPic(@RequestParam("file") MultipartFile avatarFile, @RequestParam("id")int id){
        JSONObject jsonObject = new JSONObject();
        if(avatarFile.isEmpty()){
            jsonObject.put("code",0);
            jsonObject.put("msg","文件上传失败");
            return jsonObject;
        }

        //删除原头像
        String url = consumerService.selectByPrimaryKey(id).getAvatar();
        File file=new File(System.getProperty("user.dir")+"/"+url);
        if(file.exists() && file.isFile()){
            file.delete();
        }

        //文件名=当前时间的毫秒+原来的文件名
        String fileName = System.currentTimeMillis()+avatarFile.getOriginalFilename();
        //文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"avatarImages";
        //如果文件路径不存在，新增该路径
        File file1 = new File(filePath);
        if(!file1.exists()){
            file1.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+fileName);
        //存储到数据库里的相对文件地址
        String storeAvatarPath = "/avatarImages/"+fileName;
        try {
            avatarFile.transferTo(dest);
            Consumer consumer = new Consumer();
            consumer.setId(id);
            consumer.setAvatar(storeAvatarPath);
            boolean flag = consumerService.update(consumer);
            if(flag){
                jsonObject.put("code",1);
                jsonObject.put("msg","上传成功");
                jsonObject.put("avatar",storeAvatarPath);
                return jsonObject;
            }else {
                jsonObject.put("code",0);
                jsonObject.put("msg","上传失败");
                return jsonObject;
            }
        } catch (IOException e) {
            jsonObject.put("code",0);
            jsonObject.put("msg","上传失败"+e.getMessage());
        }finally {
            return jsonObject;
        }

    }

    //前端用户登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Object login(HttpServletRequest request, HttpSession session){
        JSONObject jsonObject = new JSONObject();
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();

        if(username == null||username.equals("")){
            jsonObject.put("code",0);
            jsonObject.put("msg","用户名不能为空");
            return jsonObject;
        }
        if(password == null||password.equals("")){
            jsonObject.put("code",0);
            jsonObject.put("msg","密码不能为空");
            return jsonObject;
        }
        boolean flag = consumerService.verifyPassword(username,password);
        if(flag){
            jsonObject.put("code",1);
            jsonObject.put("msg","登录成功");
            jsonObject.put("userMsg",consumerService.getByUsername(username));
            return jsonObject;
        }
        jsonObject.put("code",0);
        jsonObject.put("msg","用户名或密码错误");
        return jsonObject;
    }

    //修改收藏或历史记录或点赞数
    @RequestMapping(value = "/addNumber", method = RequestMethod.POST)
    public void addNumber(@RequestParam("id") Integer id,
                                         @RequestParam("value") String value,
                                         @RequestParam("type") Integer type) { //0:收藏  1:历史  2:点赞视频 3:点赞评论
        String oldValue = null;
        String newValue = "";
        boolean flag = true;

        if (type == 0) {  //0:收藏
            Collections collection = new Collections();
            collection.setId(id);
            Collections collection1 = collectionService.selectByPrimaryKey(id);
            if (collection1 != null){
                oldValue = collection1.getVideoIds();
                if(oldValue != null){
                    String[] videoIds = oldValue.split("-");
                    for (int i = 0;i < videoIds.length;i++){
                        if(!value.equals(videoIds[i])){
                            newValue = newValue + videoIds[i] + "-";
                        }else{
                            flag = false;
                        }
                    }
                    if("-".equals(newValue)){
                        newValue = "";
                    }
                    if (flag){
                        newValue = value + "-" + newValue;
                    }
                    if ("".equals(newValue)){
                        newValue = "-";
                    }
                    newValue = newValue.substring(0,newValue.length()-1);
                    collection.setVideoIds(newValue);
                }else{
                    collection.setVideoIds(value);
                }
                collectionService.update(collection);
            }else{
                collection.setVideoIds(value);
                collectionService.insert(collection);
            }
        } else if(type == 1){  //1:历史
            History history = new History();
            history.setId(id);
            History history1 = historyService.selectByPrimaryKey(id);
            if (history1 != null){
                oldValue = history1.getVideoIds();
                if(oldValue != null){
                    String[] videoIds = oldValue.split("-");
                    for (int i = 0;i < videoIds.length;i++){
                        if(!value.equals(videoIds[i])){
                            newValue = newValue + videoIds[i] + "-";
                        }
                    }
                    newValue = value + "-" + newValue;
                    newValue = newValue.substring(0,newValue.length()-1);
                    history.setVideoIds(newValue);
                }else{
                    history.setVideoIds(value);
                }
                historyService.update(history);
            }else{
                history.setVideoIds(value);
                historyService.insert(history);
            }
        }else if(type == 2){  //2点赞视频
            Praise praise = new Praise();
            praise.setId(id);
            Praise praise1 = praiseService.selectByPrimaryKey(id);
            if (praise1 != null){
                oldValue = praise1.getVideoIds();
                if(oldValue != null&&!"".equals(oldValue)){
                    String[] videoIds = oldValue.split("-");
                    for (int i = 0;i < videoIds.length;i++){
                        if(!value.equals(videoIds[i])){
                            newValue = newValue + videoIds[i] + "-";
                        }else{
                            flag = false;
                        }
                    }//add:-  del:""
                    if("-".equals(newValue)){
                        newValue = "";
                    }
                    if (flag){
                        newValue = value + "-" + newValue;
                    }
                    if ("".equals(newValue)){
                        newValue = "-";
                    }
                    newValue = newValue.substring(0,newValue.length()-1);
                    praise.setVideoIds(newValue);
                }else{
                    praise.setVideoIds(value);
                }
                praiseService.update(praise);
            }else{
                praise.setVideoIds(value);
                praiseService.insert(praise);
            }
        }else if(type == 3){  //3点赞评论
            Praise praise = new Praise();
            praise.setId(id);
            Praise praise1 = praiseService.selectByPrimaryKey(id);
            if (praise1 != null){
                oldValue = praise1.getCommentIds();
                if(oldValue != null&&!"".equals(oldValue)){
                    String[] commentIds = oldValue.split("-");
                    for (int i = 0;i < commentIds.length;i++){
                        if(!value.equals(commentIds[i])){
                            newValue = newValue + commentIds[i] + "-";
                        }else{
                            flag = false;
                        }
                    }//add:-  del:""
                    if("-".equals(newValue)){
                        newValue = "";
                    }
                    if (flag){
                        newValue = value + "-" + newValue;
                    }
                    if ("".equals(newValue)){
                        newValue = "-";
                    }
                    newValue = newValue.substring(0,newValue.length()-1);
                    praise.setCommentIds(newValue);
                }else{
                    praise.setCommentIds(value);
                }
                praiseService.update(praise);
            }else{
                praise.setCommentIds(value);
                praiseService.insert(praise);
            }
        }
    }

    //根据id查询用户收藏
    @RequestMapping(value = "/getCollectionById",method = RequestMethod.GET)
    public Object getCollectionById(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        return collectionService.selectByPrimaryKey(Integer.parseInt(id));
    }
    //根据id查询用户历史记录
    @RequestMapping(value = "/getHistoryById",method = RequestMethod.GET)
    public Object getHistoryById(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        return historyService.selectByPrimaryKey(Integer.parseInt(id));
    }
    //根据id查询用户点赞记录
    @RequestMapping(value = "/getPraiseById",method = RequestMethod.GET)
    public Object getPraiseById(HttpServletRequest request){
        String id = request.getParameter("id").trim();
        return praiseService.selectByPrimaryKey(Integer.parseInt(id));
    }

    //获取性别数量
    @RequestMapping(value = "/selectBySex",method = RequestMethod.GET)
    public Object selectBySex(HttpServletRequest request){
        return statisticalService.selectBySex();
    }
}


